package com.happyscan138.makefun;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.happyscan138.makefun.Urls.Urls;
import com.happyscan138.makefun.base.isMobile;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestHandle;
import com.loopj.android.http.RequestParams;

import org.json.JSONObject;

import cz.msebera.android.httpclient.Header;

import static com.loopj.android.http.AsyncHttpClient.log;

/**
 * Created by Administrator on 2016/12/3.
 */

public class register extends AppCompatActivity implements View.OnClickListener {
    private EditText RegistUserName, RegistTelephone, RegistYanzhengma, RegistEmail, RegistPassword, RegistEnterPassword;
    private CheckBox Agree;
    private Button button_regist,button_Verifivation_Code;
    private TextView textView_land;
    private String UserName;
    private String Telephone;
    private String Yanzhengma;
    private String Passwpord;
    private String EnterPassword;
    private AsyncHttpClient registClient= registClient=new AsyncHttpClient();;
    private RequestParams params=new RequestParams();
    private boolean runningThree;
    //声明一个SharedPreferences对象和一个Editor对象
    private SharedPreferences preferences;
    private SharedPreferences.Editor editor;
    private String unionid;
    private String UId;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);
        Intent intent=getIntent();
        UserName=intent.getStringExtra("nick");
        unionid=intent.getStringExtra("unionid");
        UId=intent.getStringExtra("uid");
        initView();
    }



    public void initView() {
        TextChange textChange=new TextChange();
        RegistUserName = (EditText) findViewById(R.id.register_UserName);
        if(UserName!=null){
            RegistUserName.setText(UserName);
        }else {
            RegistUserName.addTextChangedListener(textChange);
        }
        RegistTelephone = (EditText) findViewById(R.id.regist_Telephone);
        RegistTelephone.addTextChangedListener(textChange);
        RegistYanzhengma = (EditText) findViewById(R.id.editText_yanzhengma);
        RegistYanzhengma.addTextChangedListener(textChange);
        RegistPassword = (EditText) findViewById(R.id.regist_Password);
        RegistPassword.addTextChangedListener(textChange);
        RegistEnterPassword = (EditText) findViewById(R.id.regist_Enter_Password);
        RegistEnterPassword.addTextChangedListener(textChange);
        Agree = (CheckBox) findViewById(R.id.regist_Agree);
        Agree.setChecked(true);
        button_regist = (Button) findViewById(R.id.button_Regist);
        button_regist.setOnClickListener(this);
        textView_land = (TextView) findViewById(R.id.text_to_land);
        textView_land.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        textView_land.setOnClickListener(this);
        button_Verifivation_Code=(Button)findViewById(R.id.button_Get_VerificationCode);
        button_Verifivation_Code.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_Get_VerificationCode:
                params.put("phone_no", Telephone);
                isMobile mobile = new isMobile(Telephone);
                if (mobile.isMobileNO(Telephone) == false || Telephone == null) {
                    Toast.makeText(register.this, "手机号格式不正确", Toast.LENGTH_SHORT).show();
                } else {
                    RequestHandle handleCode = registClient.post(Urls.phone_no, params, new JsonHttpResponseHandler() {
                        @Override
                        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                            super.onSuccess(statusCode, headers, response);
                            String jsonStr = response.toString();

                            try {
                                JSONObject jsonObject = new JSONObject(jsonStr);
                                String msg = jsonObject.getString("msg");

                                Toast.makeText(register.this, msg, Toast.LENGTH_LONG).show();
                                JSONObject data = jsonObject.getJSONObject("data");
                                String out_time = data.getString("time_out");
                                log.e("out_time", out_time);
                                int time = Integer.valueOf(out_time).intValue();
                                CountDownTimer downTimer = new CountDownTimer(time * 1000, 1000) {
                                    @Override
                                    public void onTick(long millisUntilFinished) {
                                        runningThree = true;
                                        button_Verifivation_Code.setText((millisUntilFinished / 1000) + "秒之后重新发送");
                                    }

                                    @Override
                                    public void onFinish() {
                                        runningThree = false;
                                        button_Verifivation_Code.setText("重新发送");
                                    }
                                };
                                if (runningThree) {
                                } else {
                                    downTimer.start();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                            super.onFailure(statusCode, headers, responseString, throwable);
                            Log.e("fail", responseString);
                        }
                    });
                }
                break;
            case R.id.button_Regist: {
                if (Yanzhengma == null || UserName == null || Passwpord == null || Telephone == null || EnterPassword == null) {
                    Toast.makeText(register.this, "请将信息填写完整", Toast.LENGTH_SHORT).show();
                } else if (Passwpord.length() < 6) {
                    Toast.makeText(register.this, "请输入6-18位密码", Toast.LENGTH_SHORT).show();
                } else if (Agree.isChecked() == false) {
                    Toast.makeText(register.this, "请选择同意使用协议", Toast.LENGTH_SHORT).show();
                } else if (Passwpord.equals(EnterPassword)) {
                    //获取preferences和editor对象
                    preferences = getSharedPreferences("UserInfo", MODE_PRIVATE);
                    editor = preferences.edit();
                    editor.putString("userName", UserName);
                    editor.putString("telephone", Telephone);
                    editor.putString("passWord", Passwpord);
                    editor.commit();

                    params.put("rand_code", Yanzhengma);
                    params.put("user_name", UserName);
                    params.put("pwd", Passwpord);
                    if(unionid!=null){
                        params.put("unionid", unionid);
                    }else {
                        params.put("unionid", "");
                    }
                    if(UId!=null){
                        params.put("uid", UId);
                    }else {
                        params.put("uid", "");
                    }
                    Log.e("params", params.toString());
                    RequestHandle handle = registClient.post(Urls.regist, params, new JsonHttpResponseHandler() {
                        @Override
                        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                            super.onSuccess(statusCode, headers, response);
                            String jsonStr = response.toString();
                            try {
                                JSONObject jsonObject = new JSONObject(jsonStr);
                                String msg = jsonObject.getString("msg");
                                Toast.makeText(register.this, msg, Toast.LENGTH_LONG).show();
                                String code = jsonObject.getString("code");
                                int Intcode = Integer.valueOf(code).intValue();
                                if (Intcode == 1) {
                                    startActivity(new Intent(register.this, Land.class));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                            super.onFailure(statusCode, headers, responseString, throwable);
                            Log.e("fail", responseString);
                        }
                    });
                } else {
                    Toast.makeText(register.this, "密码输入不一致", Toast.LENGTH_LONG).show();
                }
                break;
            }
            case R.id.text_to_land:
                startActivity(new Intent(register.this, Land.class));
                break;

        }
    }
    private class TextChange implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int start, int before, int count) {


        }

        @Override
        public void afterTextChanged(Editable s) {

            Yanzhengma = RegistYanzhengma.getText().toString();
            UserName = RegistUserName.getText().toString();
            Passwpord = RegistPassword.getText().toString();
            Telephone = RegistTelephone.getText().toString();
            EnterPassword = RegistEnterPassword.getText().toString();
        }
    }

}
